﻿
$(document).ready(function () {
    //Active current menu
    var href = $(location).prop("pathname");
    var curMenu = $("ul.navigation").find("a[href='" + href + "']");
    if (curMenu != null) {
        $(curMenu).parent().addClass("active");
        $(curMenu).closest("li.openable").addClass("active");
    }
    //Turn off autocomplete
    $("input[type='text']").prop("autocomplete","off");
});

//Reset value các control bên trong
function ResetControl(strParent) {
    var parent = $("[id$=" + strParent + "]");
    if (parent != null) {
        $("input[type='text']", parent).each(function () {
            $(this).val("");
        });
        $("input[type='hidden']", parent).each(function () {
            $(this).val("");
        });
        $("textarea", parent).each(function () {
            $(this).val("");
        });
        $("select", parent).each(function () {
            $("option[value='']", this).prop("selected", true);
        });
        $(":checkbox", parent).each(function () {
            $(this).prop("checked", false);
        });
    }
}

//Xóa dữ liệu trong 1 mảng các đối tượng
function ClearData(strObj) {
    var arr = strObj.split(",");
    if (arr != null) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = $.trim(arr[i]);
            var obj = $("[id$=" + arr[i] + "]");
            if (obj != null) {
                if (arr[i].indexOf("txt") == 0) {
                    obj.val("");
                }
                else if (arr[i].indexOf("chk") == 0) {
                    obj.prop("checked", "");
                }
                else if (arr[i].indexOf("ddl") == 0) {
                    $("option[value='']", obj).prop("selected", true);
                }
            }
        }
    }
}

//Alert box
function jAlert(msg) {
    $("#alert_box #alert_box_message").html(msg);
    $("#alert_box").dialog({
        modal: true,
        buttons: {
            Ok: function () {
                $(this).dialog("close");
            }
        }
    });
    $("#alert_box").dialog("open");
}

//Đăng ký jquery ui dialog 
function RegisterDialog() {
    $(".dialog").dialog({ autoOpen: false }).parent()
        .css('position', 'fixed')
        .appendTo($("form:first"));
}

//Mở jquery ui dialog
function OpenDialog(dialogName, _width, _height, _maxwidth, _maxheight) {
    var $this = $("#" + dialogName);
    $this.dialog({modal: true });
    if (_width != null) $this.dialog({ width: _width });
    if (_height != null) $this.dialog({ height: _height });
    if (_maxwidth != null) $this.dialog({ maxWidth: _maxwidth });
    if (_maxheight != null) $this.dialog({ maxHeight: _maxheight });
    $this.dialog("open");

    $this.keypress(function (e) {
        var keynum;
        if (window.event) {//IE
            keynum = e.keyCode;
        } else if (e.which) {// Netscape/Firefox/Opera
            keynum = e.which;
        }
        if (keynum == 13) {
            var focusedControl = $(':focus');
            if (focusedControl.prop("type") != "textarea") {
                $(this).find(":submit:eq(0)").trigger("click");
                return false;
            }
        }
    });
    return false;
}

function ValidateKeypress(numcheck, e) {
    var keynum, keychar, numcheck;
    if (window.event) {//IE
        keynum = e.keyCode;
    }
    else if (e.which) {// Netscape/Firefox/Opera
        keynum = e.which;
    }
    if (keynum == 8 || keynum == 127 || keynum == null || keynum == 9 || keynum == 0 || keynum == 13) return true;
    //Cho phép copy và paste (ctrl+c, ctrl+v)
    if (e.ctrlKey && (keynum == 99 || keynum == 118)) return true;
    keychar = String.fromCharCode(keynum);
    var result = numcheck.test(keychar);
    return result;
}

function ComboBox(strObj) {
    var arr = strObj.split(",");
    if (arr != null) {
        for (var i = 0; i < arr.length; i++) {
            var obj = $("[id$=" + $.trim(arr[i]) + "]");
            if (obj != null) {
                obj.combobox({
                    select: function (event, ui) { $(this).trigger('change'); }
                });
            }
        }
    }
}

//Datetime picker
function DateTimePicker(strObj) {
    var arr = strObj.split(",");
    if (arr != null) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = $.trim(arr[i]);
            var obj = $("[id$=" + arr[i] + "]");
            if (obj != null) {
                obj.datetimepicker({
                    addSliderAccess: true,
                    sliderAccessArgs: { touchonly: false }
                });
            }
        }
    }
}

//time picker
function TimePicker(strObj) {
    var arr = strObj.split(",");
    if (arr != null) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = $.trim(arr[i]);
            var obj = $("[id$=" + arr[i] + "]");
            if (obj != null) {
                obj.timepicker({
                    hourGrid: 4,
                    minuteGrid: 10
                });
            }
        }
    }
}

//Date picker
function DatePicker(strObj) {
    var arr = strObj.split(",");
    if (arr != null) {
        for (var i = 0; i < arr.length; i++) {
            arr[i] = $.trim(arr[i]);
            var obj = $("[id$=" + arr[i] + "]");
            if (obj != null) {
                obj.datepicker({ dateFormat: "dd/mm/yy" });
            }
        }
    }
}

//Check All checkbox
function CheckAllCheckBox(checkbox) {
    var index = $(checkbox).closest('tr').children().index($(checkbox).closest('th')); // tìm index của cột có nút CheckAll
    if (index != -1) {
        $("td:eq(" + index + ")", $("tr", $(checkbox).closest("table"))).find(":checkbox").prop("checked", checkbox.checked);
    }
}

function GuidEmpty() {
    return "00000000-0000-0000-0000-000000000000";
}

function ParseJsonDate(dateString) {
    var date = new Date(parseInt(dateString.substr(6)));
    return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
}

function ParseJsonDateTime(dateString) {
    var date = new Date(parseInt(dateString.substr(6)));
    return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

function FormatDateTime(date) {
    return (date.getMonth() + 1) + "/" +
            date.getDate() + "/" +
            date.getFullYear() + " " +
            date.getHours() + ":" +
            date.getMinutes() + ":" +
            date.getSeconds();
}

function FormatDate(date) {
    return date.getDate() + "/" +
            (date.getMonth() + 1) + "/" +
            date.getFullYear();
}

function ContainsUnicodeCharacter(str) {
    for (var i = 0, n = str.length; i < n; i++) {
        if (str.charCodeAt(i) > 127) {
            return true;
        }
    }
    return false;
}

//Show số ký tự / số tin nhắn
function ShowCount(obj) {
    var str = $(obj).val();
    var letter = str.length;
    var message = 0, letterPermessage = 0;
    if (!ContainsUnicodeCharacter(str)) {
        if (letter <= 160)
            letterPermessage = 160;
        else
            letterPermessage = 153;
    }
    else {
        if (letter <= 70)
            letterPermessage = 70;
        else
            letterPermessage = 67;
    }
    message = Math.floor(letter / letterPermessage);
    var div = letter % letterPermessage;
    if (div > 0) message += 1;
    if (message == 0) message = 1;
    $("#lbletter").html(letter);
    $("#lbmessage").html(message);
}

(function ($) {
    $.widget("custom.combobox", {
        _create: function () {
            this.wrapper = $("<span>")
            .addClass("custom-combobox")
            .insertAfter(this.element);
            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },
        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
            value = selected.val() ? selected.text() : "";
            this.input = $("<input>")
            .appendTo(this.wrapper)
            .val(value)
            .attr("title", "")
            .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
            .autocomplete({
            delay: 0,
            minLength: 0,
            source: $.proxy(this, "_source")
        })
        .tooltip({
            tooltipClass: "ui-state-highlight"
        });
        this._on(this.input, {
            autocompleteselect: function (event, ui) {
                ui.item.option.selected = true;
                this._trigger("select", event, {
                    item: ui.item.option
                });
            },
            autocompletechange: "_removeIfInvalid"
            });
        },
        _createShowAllButton: function () {
            var input = this.input,
            wasOpen = false;
            $("<a>")
            .attr("tabIndex", -1)
            .attr("title", "Show All Items")
            .tooltip()
            .appendTo(this.wrapper)
            .button({
                icons: {
                primary: "ui-icon-triangle-1-s"
            },
            text: false
        })
        .removeClass("ui-corner-all")
        .addClass("custom-combobox-toggle ui-corner-right")
        .mousedown(function () {
            wasOpen = input.autocomplete("widget").is(":visible");
        })
        .click(function () {
            input.focus();
            // Close if already visible
            if (wasOpen) {
                return;
            }
            // Pass empty string as value to search for, displaying all results
            input.autocomplete("search", "");
        });
        },
        _source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response(this.element.children("option").map(function () {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text)))
                    return {
                        label: text,
                        value: text,
                        option: this
                    };
            }));
        },
        _removeIfInvalid: function (event, ui) {
            // Selected an item, nothing to do
            if (ui.item) {
                return;
            }
            // Search for a match (case-insensitive)
            var value = this.input.val(),
            valueLowerCase = value.toLowerCase(),
            valid = false;
            this.element.children("option").each(function () {
                if ($(this).text().toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });
            // Found a match, nothing to do
            if (valid) {
                return;
            }
            // Remove invalid value
            this.input
            .val("")
            .attr("title", value + " didn't match any item")
            .tooltip("open");
            this.element.val("");
            this._delay(function () {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.data("ui-autocomplete").term = "";
        },
        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);


